package com.example.misc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import com.example.util.DBUtils;
import com.example.util.DatabaseConfig;

public class SQLQueryParser {
	
	public static void main(String... args) throws SQLException{
		String[] queries = {"create temporary table TEMP_TABLE AS (SELECT userId, firstName from users)", "select * from TEMP_TABLE"};
		
		System.out.println(new SQLQueryParser().executeQuery(queries));
	}
	
	public Object[][] executeQuery(String[] queryArray) throws SQLException{
		int queryTypeIndex = 0;
		int rowIndex = 0;
		String queryType = null;
		Object[][] results = null;
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		
		if (ArrayUtils.isNotEmpty(queryArray)){
			conn = DBUtils.getConnection(DatabaseConfig.MYSQL_LOCAL);
			
			for (String query : queryArray){
				
				if (StringUtils.isNotBlank(query)){
					queryTypeIndex = query.indexOf(" ");
					queryType = query.substring(0, queryTypeIndex);
					pstm = conn.prepareStatement(query);
					rs = null;
					
					if (queryType.equalsIgnoreCase("CREATE") || queryType.equalsIgnoreCase("INSERT")){
						pstm.execute();
					} else if (queryType.equalsIgnoreCase("SELECT")){
						rs = pstm.executeQuery();
					}
					
					
					if (rs != null){
						rs.last();
						
						results = new Object[rs.getRow()][rs.getMetaData().getColumnCount()];
						
						rs.first();
						
						for (; rs.next(); ){
							rowIndex = rs.getRow() - 1;
							
							for (int columnIndex = 0; columnIndex < rs.getMetaData().getColumnCount(); columnIndex++){
								results[rowIndex][columnIndex] = rs.getObject(columnIndex + 1);
							}
							
						}
					}
				}
			}
		}
		
		return results;
	}
}